var verification = '',
pending = 0,
timer, time = 60,      // 验证码计时器
positionX, status = 0, // 滑动手势横坐标, 界面状态
text = [{
  title: '注册', btn: '获取验证码', foot: 'English', ph1: '姓名', ph2: '手机号码', 
  note: '请输入您所收到的验证码。', sent: '验证码已发送', retry: '重新发送验证码',
  back: '修改手机号码', loading: '请稍候', 
  succ: '注册成功', fail: '注册失败，请重试。', wrong: '验证码错误，请重试',
}, {
  title: 'Register', btn: 'Get verification code', foot: '简体中文', 
  ph1: 'Name',  ph2: 'Mobile number',
  note: 'Please input the verification code you have received on your mobile phone.', 
  sent: 'Verification code has sent', retry: 'Re-send code', 
  back: 'Return and modify', loading: 'Loading', 
  succ: 'Welcome', fail: 'Registration failed, pleease retry.', wrong: 'Wrong verification code',
}], 
tips = [{ 
  toast: '您还没有选择性别哦', 
  modal: '为保证联系顺利，请填写正确的手机号码哦~' 
},{ 
  toast: 'You have not chosen the gender', 
  modal: 'Phone number error' 
}],
modal = [{
  reg: '用户数据导入', 
  regQQ: '该手机号已在QQ小程序注册，您在QQ小程序的用户数据将会导入微信小程序。',
  regWX: '该手机号已在微信小程序注册，您在微信小程序的用户数据将会导入QQ小程序。',
  reg1: '更换手机', reg2: '确定',
  exist: '手机号已存在',
  exist0: '该手机号已在QQ小程序或微信小程序中注册。请检查姓名是否匹配，或重新输入手机号码。'
}];

Page({
  data: {
    code: [{ id: 0, num: '' }, { id: 1, num: '' }, { id: 2, num: '' }, { id: 3, num: '' }],
    form: { gender: 2, name: '', phone: '' }, // 表单
    inpNum: '',         // 验证码框默认为空
    focus: 1,           // 验证码输入框聚焦
    verify: false,      // 是否处于验证码填写界面
    disabled: true,     // 黄色按钮是否禁用
    phoneFocus: false,  // 手机输入聚焦：用于输入完毕撤下键盘
    manualSlide: false, // 是否支持手动滑屏：用于左右滑动
    src: '/assets/logo/',
    btnClr: '#ffeec6',
    time: '',           // 显示在按钮上的时间
    opacity: [.2, .2],// 性别选框背景透明度：选中为.7，未选中为.2
  },

  onReady() {
    this.setData({ text: text[wx.lang] });
    this.bg_color = wx.createAnimation({
      duration: 500,
      timingFunction: 'linear',
    });
    // verification = Math.floor(Math.random() * 8999 + 1000).toString();
  },

  onShow() {
    wx.setStorageSync('theme', '#aaaffb');
    wx.show(this, ['show1', 'show2', 'show3', 'show4', 'show5']);
    wx.onShow(this, text[wx.lang].title, '#fcc1d6');
  },
  
  _manualSlide(e) {
    positionX = e.changedTouches[0].pageX;
  },
  manualSlide(e) {
    if (!this.data.manualSlide) return;
    let newX = e.changedTouches[0].pageX,
    delta = wx.system.width / 5;
    if (positionX - newX > delta && !status) this.slide();
    else if (newX - positionX > delta && status) this.modify();
  },

  changeColor(e) {
    let target = parseInt(e.currentTarget.id);
    let form = this.data.form;
    form.gender = target;
    this.setData({ form: form });
    let color = '#fcc1d6';
    wx.setStorageSync('theme', '#fcc1d6');
    if (target) {
      color = '#aaaffb';
      wx.setStorageSync('theme', '#aaaffb');
    };
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: color,
      animation: {
        duration: 500,
        timingFunc: 'linear',
      },
    })
    this.bg_color.opacity(target).step();
    this.setData({
      bg: this.bg_color.export(),
      opacity: [target ? .2 : .7, target ? .7  : .2],
    })
  },

  changeLanguage() {
    var newLanguage = wx.lang ? 0 : 1;
    wx.setStorageSync('language', newLanguage);
    wx.lang = newLanguage;
    wx.setNavigationBarTitle({
      title: text[wx.lang].title,
    })
    this.setData({ text: text[wx.lang] });
  },
  
  inp(e) {
    let form = this.data.form;
    form[e.currentTarget.id] = e.detail.value;
    this.setData({ form: form });
    if (e.currentTarget.id == 'phone' && form.phone[10])
      this.setData({ phoneFocus: false });
    if (form.name == '' || !form.phone[10])
      this.setData({ btnClr: '#ffeec6;', disabled: true });
    else
      this.setData({ btnClr: '#f4d66d;', disabled: false });
  },

  codeInp(e) {
    let code = this.data.code;
    for (var i = 3; i >= 0; --i)
      code[i].num = '';
    for (++i; i < e.detail.value.length; ++i)
      code[i].num = e.detail.value[i];
    this.setData({ code: code });
    if (e.detail.value.length == 4) {
      this.setData({ focus: 0 });
      return this.register();  // 进入注册流程
    }
  },

  // 点击输入框 & 聚焦
  codeTap(e) {
    let i = 0,
      id = parseInt(e.currentTarget.id),
      code = this.data.code,
      newNum = '';
    for (; i < id; ++i)
      newNum += code[i].num;
    for (; i < 3; ++i) 
      code[i].num = '';
    this.setData({ 
      focus: 1, 
      code: code,
      inpNum: newNum
    });
  },

  getCode(r) {
    if (this.data.form.gender == 2) { wx.toast(tips[wx.lang].toast); return; }
    let info = r.detail.userInfo, form = this.data.form;
    if (!info) return;
    form.nickName = info.nickName,
    form.avatar = info.avatarUrl;
    this.setData({ form: form });
    var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[8-9]{1}))+\d{8})$/;
    if (this.data.form.phone != '' && !myreg.test(this.data.form.phone)) {
      wx.modal(0, tips[wx.lang].modal);
      return;
    }
    this.setData({ btnClr: '#ffeec6;', disabled: true });
    // 判断该用户是否在其他客户端注册过
    let smsParams = {
      phoneNumber: this.data.form.phone,
      templateId: 515017
    }  
    wx.post('User.findByPhone', smsParams, res => {
      if (res.errCode) {
        if (res.data.name == form.name) {   // 若手机号、姓名为同一用户
          let content = wx.Config.client ? modal[wx.lang].regQQ : modal[wx.lang].regWX;
          wx.modal(modal[wx.lang].reg, content, modal[wx.lang].reg1, modal[wx.lang].reg2,
          null, null, () => {  
            this.timer();
            wx.post('Weixin.sendSMS', smsParams, res => {
              if (res.data.errmsg == 'OK') this.slide();
              else wx.toast(res.data.errmsg);
            }, text[wx.lang].loading)
          }, () => {  // 重新输入手机号
            this.setData({ btnClr: '#f4d66d;', disabled: false });
          })
        } else {     // 若不为同一用户，则提示重新输入手机号
          wx.modal(modal[wx.lang].exist, modal[wx.lang].exist0, null,  modal[wx.lang].reg2,
          null, null, () => {   // 重新输入手机号
            this.setData({ btnClr: '#f4d66d;', disabled: false });
          })
        }
      } else {
        wx.post('Weixin.sendSMS', smsParams, res => {
          if (res.data.errmsg == 'OK') this.slide();
          else wx.toast(res.data.errmsg);
        }, text[wx.lang].loading)
      }
    }, text[wx.lang].loading)
  },

  register() {
    if (pending++) return;

    let _v = '';
    for (let i = 0; i < 4; ++i) _v += this.data.code[i].num[0];
    let userBasicInfo = this.data.form,
      url = wx.Config.client ? 'wxRegister' : 'qqRegister',
      id = wx.Config.client ? 'openid' : 'qqid';
    userBasicInfo.idUser = wx.appData.user.iduser;
    userBasicInfo[`${id}`] = wx.appData.user[`${id}`];

    wx.post(`User.${url}`, { userBasicInfo, params: parseInt(_v).toString() }, res => {
      if (res.errCode == 101) {
        wx.toast(text[wx.lang].wrong, 0, 1, () => {
          let code = this.data.code;
          for (let i = 0; i < 4; ++i) code[i].num = '';
          this.setData({ code: code, inpNum: '' });
          setTimeout(() => {
            this.setData({
              focus: 1
            });
          }, 1000);
        }, 1000);
      } else if (res.success) {
        console.log('跳转了')
        wx.appData.user = res.data;
        wx.reLaunch({ url: '../../module/index/me/me' });
        wx.toast(text[wx.lang].succ, 1);
      } else {
        wx.toast(text[wx.lang].fail);
      }
      pending = 0;
    }, text[wx.lang].loading);
  },


  // 向左滑动
  modify() {
    let arr1 = ['show1', 'show2', 'show3', 'show4', 'show5'];
    let arr2 = ['show1', 'show6', 'show7', 'show8'];
    wx.slide_h(this, arr2, wx.system.width, 0, .5, () => {
      wx._slide_h(this, arr1, -1 * wx.system.width, 0, () => {
        this.setData({
          focus: [0, 0, 0, 0],
          verify: false,
          disabled: true,
          btnClr: '#ffeec6;',
        });
        wx.slide_h(this, arr1, 0, 1, 1, () => {
          --status; // 处于信息输入界面
        })
      });
    });
  },

  // 向右滑动
  slide() {
    let arr1 = ['show1', 'show2', 'show3', 'show4', 'show5'];
    let arr2 = ['show1', 'show6', 'show7', 'show8'];
    wx.slide_h(this, arr1, -1 * wx.system.width, 0, .5, () => {
      wx._slide_h(this, arr2, wx.system.width, 0, () => {
        this.setData({
          verify: true,
          manualSlide: true,
          disabled: true,
          btnClr: '#ffeec6;',
        });
        wx.slide_h(this, arr2, 0, 1, 1, () => {
          this.setData({ focus: [1, 0, 0, 0] });
          ++status; // 处于验证码输入界面
        })
      });
    });
  },

  timer() {
    clearTimeout(timer);
    if (time < 0){
      time = 60;
      this.setData({ time: '', btnClr: '#f4d66d;', disabled: false });
    } else {
      timer = setTimeout(() => {
        this.setData({ time: ' (' + time.toString() + ')' });
        this.timer(time--);
      }, 1000);
    }
  },
})